<template>
  <div>
    <a-card>
      <p class="text-lg font-bold">设置角色</p>
      <a-row>
        <a-col :span="12">
          <a-form :model="formState">
            <a-form-item>
              <a-checkbox-group
                v-model:value="formState.role_ids"
                style="width: 100%"
              >
                <a-row>
                  <a-col :span="6" v-for="(r, index) in roles">
                    <a-checkbox :value="r.id">{{ r.name }}</a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSubmit">提交</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import Api from "@/api/backend/api";
const route = useRoute();
const router = useRouter();
const id = route.params.id;
const roles = ref([]);
const formState = reactive({
  user_id: id,
  role_ids: [],
});
const getUserRole = async () => {
  const userRoles = await Api.userController.hasRole({
    user_id: id,
  });
  formState.role_ids = userRoles.map((item) => {
    return item.id;
  });
};
const getRoles = async () => {
  roles.value = await Api.roleController.index();
};

const init = async () => {
  await getUserRole();
  await getRoles();
};
init();

const onSubmit = async () => {
  await Api.userController.setRole(formState);
  setTimeout(() => {
    router.go(-1);
  }, 500);
};
</script>

<style></style>
